<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

class Questions_Controller extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->helper('xlsimport/php-excel-reader/excel_reader2');
        $this->load->helper('xlsimport/spreadsheetreader.php');
        $this->load->model('qbank_model', '', true);
        $this->load->model('user', '', true);

        if (!$this->session->userdata('logged_in')) {
            redirect('login');
        }

        //$this->LoggedUser = $this->user->getLoggedUser();

        $this->load->library('authentication');
        $this->load->helper('t');
        $this->loggedUser = $this->authentication->getLoggedUser();
        $this->authentication->redirectIfNotBe(array('HR', 'SC'));
    }

    function index($category = 'all', $difficult = 'all') {

        $this->load->helper('form');
        $this->load->model('category', '', TRUE);
        $this->load->model('difficult_level', '', TRUE);
        $this->load->model('quiz_model', '', TRUE);
        $this->load->model('evaluation', '', TRUE);
        
        $evaluation = $this->evaluation->get_last();
        
        // lấy danh sách câu hỏi theo điều kiện tìm
        $criteria = array();
        if($category != 'all')
        {
            $criteria['cid'] = $category;
        }
        if($difficult != 'all')
        {
            $criteria['did'] = $difficult;
        }
        $questions = $this->qbank_model->get($criteria);

        // từ điển chủ đề
        $categories = $this->category->category_dropdown();
        $viewData['category'] = $categories;        
        $cateDic = array();
        foreach ($categories as $value) {
            $cateDic[$value->cid] = $value->category_name;
        }
        $viewData['cateDic'] = $cateDic;
        
        // từ điển mức độ khó
        $difficulties = $this->difficult_level->level_dropdown();
        $viewData['difficult_level'] = $difficulties;
        $diffDic = array();
        foreach ($difficulties as $value) {
            $diffDic[$value->did] = $value->level_name;
        }
        $viewData['diffDic'] = $diffDic;
        
        // thống kê đúng sai của từng câu hỏi trong đợt đánh giá hiện tại
        foreach ($questions as &$eachQuestion) {
            $eachQuestion['rights'] = $this->quiz_model->getNumberOfRights($eachQuestion['qid'], $evaluation['id']);            
            $eachQuestion['wrongs'] = $this->quiz_model->getNumberOfWrongs($eachQuestion['qid'], $evaluation['id']);;
            $eachQuestion['rightsRatio'] = $eachQuestion['rights']/($eachQuestion['rights'] + $eachQuestion['wrongs'])*100;
            $eachQuestion['wrongsRatio'] = $eachQuestion['wrongs']/($eachQuestion['rights'] + $eachQuestion['wrongs'])*100;
        }
        
        $viewData['result'] = $questions;//$this->qbank_model->question_list($limit);        
        $viewData['filterCategory'] = $category;
        $viewData['filterDifficult'] = $difficult;
        
        //$viewData['title'] = "Question Bank";
        
        //$viewData['LoggedUser'] = $this->LoggedUser;

        $this->load->view(get_folder($this->loggedUser->title) . '/questions_list', $viewData);
    }

    function import() {
//        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }
        if (isset($_FILES['xlsfile'])) {
            $targets = 'xls/';
            $targets = $targets . basename($_FILES['xlsfile']['name']);
            $docadd = ($_FILES['xlsfile']['name']);
            if (move_uploaded_file($_FILES['xlsfile']['tmp_name'], $targets)) {
                $Filepath = $targets;
                $allxlsdata = array();
                date_default_timezone_set('UTC');

                $StartMem = memory_get_usage();
                //echo '---------------------------------'.PHP_EOL;
                //echo 'Starting memory: '.$StartMem.PHP_EOL;
                //echo '---------------------------------'.PHP_EOL;

                try {
                    $Spreadsheet = new SpreadsheetReader($Filepath);
                    $BaseMem = memory_get_usage();

                    $Sheets = $Spreadsheet->Sheets();

                    //echo '---------------------------------'.PHP_EOL;
                    //echo 'Spreadsheets:'.PHP_EOL;
                    //print_r($Sheets);
                    //echo '---------------------------------'.PHP_EOL;
                    //echo '---------------------------------'.PHP_EOL;

                    foreach ($Sheets as $Index => $Name) {
                        //echo '---------------------------------'.PHP_EOL;
                        //echo '*** Sheet '.$Name.' ***'.PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;

                        $Time = microtime(true);

                        $Spreadsheet->ChangeSheet($Index);

                        foreach ($Spreadsheet as $Key => $Row) {
                            //echo $Key.': ';
                            if ($Row) {
                                //print_r($Row);
                                $allxlsdata[] = $Row;
                            } else {
                                var_dump($Row);
                            }
                            $CurrentMem = memory_get_usage();

                            //echo 'Memory: '.($CurrentMem - $BaseMem).' current, '.$CurrentMem.' base'.PHP_EOL;
                            //echo '---------------------------------'.PHP_EOL;

                            if ($Key && ($Key % 500 == 0)) {
                                //echo '---------------------------------'.PHP_EOL;
                                //echo 'Time: '.(microtime(true) - $Time);
                                //echo '---------------------------------'.PHP_EOL;
                            }
                        }

                        //	echo PHP_EOL.'---------------------------------'.PHP_EOL;
                        //echo 'Time: '.(microtime(true) - $Time);
                        //echo PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;
                        //echo '*** End of sheet '.$Name.' ***'.PHP_EOL;
                        //echo '---------------------------------'.PHP_EOL;
                    }
                } catch (Exception $E) {
                    echo $E->getMessage();
                }


                $this->qbank_model->import_question($allxlsdata);
            }
        } else {
            echo "Error: " . $_FILES["file"]["error"];
        }
        redirect(get_folder($this->loggedUser->title).'/questions');
    }

    function export() {

        $questions = $this->qbank_model->get_list();
        $toExport = array();
        $i = 1;

        foreach ($questions as $eachQuestion) {

            $row = array(
                'No' => $i,
                'Category' => $eachQuestion['category_name'],
                'Level' => $eachQuestion['level_name'],
                'Question' => $eachQuestion['question'],
                'Correct option number' => '',
//                'Option 1' => $eachQuestion['options']['0']['option_value'],
//                'Option 2' => $eachQuestion['options']['1']['option_value'],
//                'Option 3' => $eachQuestion['options']['2']['option_value'],
//                'Option 4' => $eachQuestion['options']['3']['option_value']
            );

            $j = 0;
            foreach ($eachQuestion['options'] as $eachOption) {
                $row['Option ' . ($j + 1)] = $eachOption['option_value'];
                if ($eachOption['score'] == '1') {
                    $row['Correct option number'] = $j + 1;
                }
                $j++;
            }

            $toExport[] = $row;
            $i++;
        }

//        download_send_headers("data_export_" . date("Y-m-d") . ".csv");
//        echo array2csv($toExport);



        $str = ConvertToCSV($toExport);
        $CSVString = preg_replace("/(^[\r\n]*|[\r\n]+)[\s\t]*[\r\n]+/", "\n", $str);
        //$CSVString = preg_replace('/^\n+|^[\t\s]*\n+/m','', $CSVString);
        
        //header("Content-type: application/octet-stream");
        header("Content-type: text/csv");
        header("Content-Disposition: attachment; filename=questions.csv");
        //header('Content-length: ' . strlen($CSVString));
        header("Expires: 0");
        //header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
        header("Pragma: no-cache");//header("Pragma: public");
        
        
        echo $CSVString;
    }

    function add_new() {

        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }
        $this->load->model('category', '', TRUE);
        $data['category'] = $this->category->category_dropdown();
        $this->load->model('difficult_level', '', TRUE);
        $data['difficult_level'] = $this->difficult_level->level_dropdown();

        if ($this->input->post('cid')) {
            $data['resultstatus'] = $this->qbank_model->add_question();
        }
        $data['title'] = "Add new question";

        $this->load->view(get_folder($this->loggedUser->title) . '/question_add_new', $data);
    }

    function edit_question($id) {

//        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }


        $this->load->model('category', '', TRUE);
        $viewData['category'] = $this->category->category_dropdown();

        $this->load->model('difficult_level', '', TRUE);
        $viewData['difficult_level'] = $this->difficult_level->level_dropdown();

        if ($this->input->post('cid')) {
            //print_r($_POST);
            $viewData['resultstatus'] = $this->qbank_model->update_question($id);
        }
        $viewData['result'] = $this->qbank_model->get_question($id);

        $viewData['title'] = "Edit question";

        $this->load->view(get_folder($this->loggedUser->title) . '/question_edit', $viewData);
    }

    function remove_question($id) {
//        $logged_in = $this->session->userdata('logged_in');
//        if ($logged_in['su'] != "1") {
//            exit('Permission denied');
//            return;
//        }
        $viewData['resultstatus'] = $this->qbank_model->remove_question($id);

        redirect(get_folder($this->loggedUser->title).'/questions', 'refresh');
    }
    
    function stat_option() {
        $questionId = $_POST['questionId'];
        $temp = explode('-', $questionId);
        $questionId = $temp[1];
        
        $json = array();
//        if($questionId == 0)
//        {
//            $json = array('success' => false, 'message' => 'Không tìm thấy câu hỏi.');
//        }
//        else
//        {
//            $json = array('success' => true, 'data' => array());
//        }
        // truy vấn các option của câu hỏi
        $this->load->model('QuestionOption');
        $options = $this->QuestionOption->get_by_question($questionId);
        
        // thống kê cho từng option, gán vào kết quả trả về
        if($options == false)
        {
            $json = array('success' => false, 'message' => 'Không tìm thấy các lựa chọn của câu hỏi.');
        }
        else {
            $json = array('success' => true);
            $data = array();
            $wrongs = 0;
            foreach ($options as $eachOption) {
                // thống kê cho option
                $this->load->model('evaluation');
                $evaluation = $this->evaluation->get_last();
                $selectedNumber = $this->QuestionOption->get_number_of_selected($questionId, $eachOption['oid'], $evaluation['id']);
                $data[] = array($eachOption['option_value'], $eachOption['score'], $selectedNumber);
                if ($eachOption['score'] == 0)
                {
                    $wrongs += $selectedNumber;
                }
            }
            // bỏ trống (không làm câu hỏi này)
            $this->load->model('quiz_model');
            $noAnswer = $this->quiz_model->getNumberOfWrongs($questionId, $evaluation['id']) - $wrongs;
            $data[] = array('Bỏ trống (không trả lời)', 0, $noAnswer);
            
            $json['result'] = $data; 
        }

        header("content-type:application/json");
        echo json_encode($json);
    }

// get desired question for particular subject and difficulty level
    function get_level_question($difficulty_level, $category) {
        $this->db->where("cid", $category);
        $this->db->where("did", $difficulty_level);
        $query = $this->db->get("qbank");
        $num = $query->num_rows();
        echo $num;
    }

}
?>